package Dao.DaoImpl;

import Dao.RepairDao;
import Utils.JDBCUtils;
import domain.Repair;
import domain.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class RepairDaoImpl implements RepairDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Repair> fuzzySelectRepqir(HashMap<String, String> map) {

        String sql = "select * from repair where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        Set<String> set = map.keySet();
        List<Object> params = new ArrayList<Object>();
        for (String key : set) {
            String value = map.get(key);

            //判断value是否有值
            if(value!=null && !"".equals(value)){
                //有值就拼接
                sb.append(" and "+key+" like ?");
                params.add("%"+value+"%");//上面 ? 的值
            }
        }
        sql = sb.toString();
        return template.query(sql,new BeanPropertyRowMapper<Repair>(Repair.class),params.toArray());
    }

    @Override
    public List<Repair> repairList() {
        String sql = "select * from repair";
        return template.query(sql,new BeanPropertyRowMapper<>(Repair.class));
    }

    @Override
    public Repair selectRepairById(String id) {
        String sql ="select * from repair where id=?";

        return template.queryForObject(sql,new BeanPropertyRowMapper<>(Repair.class),id);
    }

    @Override
    public void updateRepair(Repair repair) {
        String sql="update repair set dormnum=?,problem=?,description=?,isfinish=? where id = ?";
        template.update(sql,repair.getDormnum(),repair.getProblem(),repair.getDescription(),repair.getIsfinish(),repair.getId());
    }

    @Override
    public void deleteRepair(String id) {
        String sql ="delete from repair where id=?";
        template.update(sql,id);

    }

    @Override
    public void addRepair(Repair repair) {
        String sql = "insert into repair values(null,?,?,?,?,null)";
        template.update(sql,repair.getDormnum(),repair.getProblem(),repair.getDescription(),repair.getIsfinish());
    }

    @Override
    public void updateIsFinish(int id,String checkPeo, String flag) {
        String sql ="update repair set isfinish=?,checkPeo=? where id=?";
        template.update(sql,flag,checkPeo,id);
    }

    @Override
    public List<Repair> showNotReadRepair() {
        String sql ="select * from repair where isfinish='false'";
        return template.query(sql,new BeanPropertyRowMapper<>(Repair.class));
    }
}
